import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:s_utils/s_utils.dart';

class IInterceptors extends InterceptorsWrapper {
  final String env;
  final String? apiKey;
  final bool PROD = kReleaseMode;
  final bool showApiLog;

  IInterceptors({required this.env, this.apiKey, this.showApiLog = true});

  @override
  Future onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
    Map<String, dynamic> headers = await SHttp.getHeaders();
    options.headers = headers;
    if (showApiLog && !PROD) {
      String title = "";
      if(options.extra['@cache_options@'] != null) {
        CacheOptions? cacheOptions = CacheOptions.fromExtra(options);
        if(cacheOptions?.policy == CachePolicy.forceCache) title = "缓存提取 ";
      }
      logger.i("${options.method.toUpperCase()}:${title} ${options.uri}, data: ${options.data},"
          "token: ${headers['Authorization']}, "
          "apiKey: ${headers['Api-Key']}, "
          "Accept-Language: ${headers['Accept-Language']}");
    }
    super.onRequest(options, handler);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    if (showApiLog && !PROD) logger.e(
        "${err.requestOptions.method} ${err.response?.statusCode} "
            "ERROR>> URL: ${err.requestOptions.uri} "
            "ErrorData $err, ${err.response?.data} "
    );
    super.onError(err, handler);
  }

}
